<?php

namespace App\App\Services;

use App\Http\Responses\RespondsJson;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class VMSService
{
    use RespondsJson;
    private $VMSUrl = '';
    private $partnerToken = '';
    private $partnerCode = '';
    private $storagePath = '';
    private $siteAlias = '';
    private $videoUrl = 'morefun/source/http/2017/5/9/videotest.mp4';
    private $fileName = 'videotest.mp4';
    private $source = 'source';
    private $method = 'ftp';
    private $mimeType = '';
    private $viceMimeType = [
        'audio/mp3',
        'audio/midi',
        'audio/mpeg',
        'audio/ogg',
        'audio/x-m4a',
        'audio/x-realaudio',
    ];
    const METHOD_FTP_UPLOAD_VIDEO = 'ftpUploadVideo';
    const METHOD_FTP_UPLOAD_AUDIO = 'ftpUploadAudio';
    const METHOD_DELETE_DATA_BY_IDS = 'deleteDataByIds';
    const DELETE_COMPLETELY = 0;
    const DELETE_TO_RECYCLE = 1;
    const TYPE_VIDEO = 5;
    const TYPE_AUDIO = 6;
    const TYPE_OPERA = 7;

    public function __construct()
    {
        $this->VMSUrl = config('vms.url');
        $this->partnerToken = config('vms.token');
        $this->partnerCode = config('vms.code');
        $this->storagePath = config('vms.storage_path');
        $this->siteAlias = config('vms.site_alias');
    }

    /**
     * 保存文件到VMS存储
     * @param UploadedFile $file
     * @return bool|string
     */
    public function uploadVideoTmp(UploadedFile $file)
    {
        //siteAlias/source/ftp/2014/8/11/abc.mp4
        $now = Carbon::now();
        $year = $now->year;
        $month = $now->month;
        $day = $now->day;
        //$location = $this->siteAlias . DIRECTORY_SEPARATOR . $this->source . DIRECTORY_SEPARATOR . $this->method . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month . DIRECTORY_SEPARATOR . $day;
        //账号登录后已经包含存储规划站点根路径
        $location = $this->source . DIRECTORY_SEPARATOR . $this->method . DIRECTORY_SEPARATOR . $year . DIRECTORY_SEPARATOR . $month . DIRECTORY_SEPARATOR . $day;
        if ($file instanceof UploadedFile) {
            $fileOriginalName = $file->getClientOriginalName();
            $fileExtension = $file->getClientOriginalExtension();
            $this->mimeType = $file->getClientMimeType();
            try {
                $fileName = Uuid::uuid4()->toString();
                $result = Storage::disk('ftp')->putFileAs($location, $file, $fileName . '.' . $fileExtension);
                if ($result) {
                    $this->videoUrl = $this->siteAlias . DIRECTORY_SEPARATOR . $location . DIRECTORY_SEPARATOR . $fileName . '.' . $fileExtension;
                    $this->fileName = $fileOriginalName;
                    //					$this->ftpUploadVideo();
                    return true;
                } else {
                    return 'upload fail';
                }
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        } else {
            return 'file is invalid';
        }
    }

    /**
     * 上传文件到VMS
     * @return mixed
     */
    public function ftpUploadVideo()
    {
        if (empty($this->videoUrl)) {
            throw new \RuntimeException('需先调用uploadVideoTmp以上传文件到VMS存储');
        }

        if (config('app.debug')) {
            Log::debug($this->videoUrl);
        }
        $transcodeGroup = app()['config']['vms.vms_video_trans_code_group'];
        if(in_array($this->mimeType, $this->viceMimeType)){
            $transcodeGroup = app()['config']['vms.vms_vice_trans_code_group'];
        }
        $requestData = [
            'partnerToken' => $this->partnerToken,
            'method' => self::METHOD_FTP_UPLOAD_VIDEO,
            'isPublish' => 1,
            'contentinfo' => [
                [
                    'title' => $this->fileName,
                    'videourl' => $this->videoUrl,
                    'description' => '魔方互动上传',
                    'tags' => '魔方互动',
                    'transcodeGroup' => $transcodeGroup,
                ]
            ],
        ];

        try {
            $client = new Client();
            $result = $client->post($this->VMSUrl . '/ImportInterfacesService', ['body' => json_encode($requestData)]);
            if ($result->getStatusCode() == 200) {
                $responseData = $result->getBody();
                Log::debug($responseData);
                $responseResult = json_decode($responseData, true);
                if (isset($responseResult['resultCode'])) {
                    return $responseResult['message'];
                }
                if (@$responseResult['interfaceStatus'] === 1) {
                    return $responseResult['conJa'];
                } else {
                    return $responseResult['interfaceMessage'];
                }
            } else {
                Log::debug($result->getReasonPhrase());
                return '请求VMS失败';
            }
        } catch (\Exception $exception) {
            Log::debug($exception->getMessage());
            return $exception->getMessage();
        }
    }

    /**
     * VMS回调响应数据
     * @param $sourceID mixed 资源ID
     * @param $status mixed 资源状态
     * @param $message string 消息
     * @return \Illuminate\Http\JsonResponse
     */
    public function callbackResponse($sourceID, $status, $message)
    {
        return $this->respondJson(
            [
                'id' => $sourceID,
                'partnerCode' => $this->partnerCode,
                'status' => $status,
                'message' => $message
            ],
            200,
            [
                'Access-Control-Allow-Origin' => '*'
            ]
        );
    }

    /**
     * 按照ID删除VMS资源
     * @param $resourceID
     * @return mixed|string
     */
    public function deleteDataByIds($resourceID)
    {
        if (is_array($resourceID)) {
            $resourceID = implode(',', $resourceID);
        }

        try {
            $requestData = [
                'partnerToken' => $this->partnerToken,
                'method' => self::METHOD_DELETE_DATA_BY_IDS,
                'sourceIDs' => $resourceID,
                'sourceType' => self::TYPE_AUDIO,
                'delType' => self::DELETE_COMPLETELY
            ];

            $client = new Client();
            $response = $client->post(
                $this->VMSUrl . '/APIServiceReceiver',
                [
                    'body' => json_encode($requestData)
                ]
            );

            if ($response->getStatusCode() != 200) {
                return $response->getReasonPhrase();
            }

            $responseData = $response->getBody();

            if (config('app.debug')) {
                Log::debug($responseData);
            }

            return json_decode($responseData, true);
        } catch (\Exception $exception) {
            return $exception->getMessage();
        }
    }
}
